<template>
	<div class="container"></div>
</template>

<script>
import { Dialog  } from 'vant';
import storage from '@/model/storage'
import { wxlogin , loginIn } from '@/model/api';
import { appId } from '@/util';
	export default {
		data() {
            return {
               code: '', // 前端获取 code 传给后端调用相应接口
               inviteId:"",
            }
		},
		created() {
            let { inviteId = "0" , code } = this.$route.query;
			
			if(code) { // 存在 code 直接调用接口
                this.code = code;
                this.inviteId = inviteId;
				this.handGetUserInfo();
			}else{
                this.handLogin();
            }
		},
		methods: {
			handLogin() {
				if(process.env.NODE_ENV === 'production'){ //生产环境进行WXLogin
					// 重定向地址重定到当前页面，在路径获取 code
					const hrefUrl = window.location.href;
					if (this.code === '') {
						window.location.href = `
							https://open.weixin.qq.com/connect/oauth2/authorize
							?appid=${appId}
							&redirect_uri=${encodeURIComponent(hrefUrl)}
							&response_type=code
							&scope=snsapi_userinfo
							&state=CSDN_state#wechat_redirect
						`
					}
				}else{ //开发环境 直接登录
                    loginIn({account:15515974821,password:123456}).then( res => {
						if(res.code == 1){
							storage.set('userToken',res.data);
							this.$router.push({name:"tabmain"})
						}
					})
				}
			},	
			async handGetUserInfo() {
                let { code , data , msg } = await wxlogin({code:this.code,id:this.inviteId});
                if(code == 1){ //登录成功
					this.$toast({
						type:"success",
						message:"登录成功,请先设置支付密码和收货地址"
					})
					storage.set('userToken',data)
					setTimeout(() => {
						let loginPath = storage.get('loginPath');
						if(loginPath){
                           window.location.href = "http://syb.longxiaokj.com"+ loginPath;
						}else{
                           window.location.href = "http://syb.longxiaokj.com/tabmain";
						}
					},600)
                }else{
                    Dialog.alert({
						title: '提示',
						message: msg,
						theme: 'round-button',
						confirmButtonText:"重新登录",
						cancelButtonText:"返回首页",
					}).then(() => {
						this.handLogin();
					}).catch(() => {
						this.$router.push({name:"/tabmain"})
					});
                }
			},
		},
	}
</script>